

#import "PUFoodDetailsVC.h"
#import "PUFoodDetailsCell.h"
#import "PUFoodDetailsView.h"
#import "PUPhoneLogin.h"
@interface PUFoodDetailsVC ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)PUFoodDetailsView *headerView;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UIButton *collectBtn;

@end

@implementation PUFoodDetailsVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.model.name;
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor=[UIColor whiteColor];
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//设置分隔线样式
    self.tableView.bounces = YES;
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.view addSubview:self.tableView];
    self.edgesForExtendedLayout = UIRectEdgeTop;
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.tableView registerClass:PUFoodDetailsCell.class forCellReuseIdentifier:@"CPFoodDetailsCell"];
    
    self.headerView = [[PUFoodDetailsView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_width+40)];
    self.headerView.model = self.model;
    self.tableView.tableHeaderView = self.headerView;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset = 0;
    }];
    
    self.collectBtn = [[UIButton alloc]init];
    self.collectBtn.selected = self.model.isCollect;
    [self.collectBtn setTitle:@" 收藏" forState:UIControlStateNormal];
    [self.collectBtn setTitle:@" 已收藏" forState:UIControlStateSelected];
    self.collectBtn.titleLabel.textColor = UIColor.whiteColor;
    self.collectBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [self.collectBtn setImage:[UIImage imageNamed:@"收藏_未选中2"] forState:UIControlStateNormal];
    [self.collectBtn setImage:[UIImage imageNamed:@"收藏_选中2"] forState:UIControlStateSelected];
    [self.collectBtn addTarget:self action:@selector(collectAction) forControlEvents:UIControlEventTouchUpInside];
    self.collectBtn.backgroundColor = [UIColor colorWithHex:0xFF729A];
    self.collectBtn.clipsToBounds = true;
    self.collectBtn.layer.cornerRadius = 48/2;
    [self.view addSubview:self.collectBtn];
    [self.collectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset = 0;
        make.width.offset = 200;
        make.height.offset = 48;
        make.bottom.offset = -kSafeAreaBottomHeight - 15;
    }];
    if ([Config getToken]!=nil) {
        [self historydata];
    }
    
}

- (void)collectAction {
    if ([Config getToken]==nil) {
        [self noLogin];
        return;
    }
    
    [self collectdata];
    self.model.isCollect = !self.model.isCollect;
    self.collectBtn.selected = self.model.isCollect;
    
    
    if (self.collectBtn.selected) {
        self.model.count ++;
    }
    else {
        self.model.count --;
    }
}

-(void)noLogin{
    PUPhoneLogin *vc=[[PUPhoneLogin alloc]init];
    UINavigationController *navVc = [[UINavigationController alloc] initWithRootViewController:vc];
    navVc.modalPresentationStyle=0;
    [self presentViewController:navVc animated:NO completion:nil];
}

//获取当前的时间
-(NSString*)getCurrentTimes{
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
     [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
     //现在时间,你可以输出来看下是什么格式
     NSDate *datenow = [NSDate date];
     //----------将nsdate按formatter格式转成nsstring
     NSString *currentTimeString = [formatter stringFromDate:datenow];
     NSLog(@"currentTimeString =  %@",currentTimeString);
     return currentTimeString;
}
-(void)historydata{
    //创建一个归档文件夹
    NSArray *library = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *strLib = [[library objectAtIndex:0] stringByAppendingPathComponent:@"archive"];
    BOOL directory = YES;
    if (![[NSFileManager defaultManager] fileExistsAtPath:strLib isDirectory:&directory])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:strLib withIntermediateDirectories:NO attributes:nil error:nil];
    }
    //归档
    NSString *entityArchive = [strLib stringByAppendingPathComponent:[NSString stringWithFormat:@"historyDataArchive%@",[Config getID]]];
//    [NSKeyedArchiver archiveRootObject:data toFile:entityArchive];
    //数据源从归档中读出
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:entityArchive];
    NSLog(@"%@",array);
    if(array.count==0){
        array=[NSMutableArray array];
    }
    
    for (int i=0; i<array.count; i++) {
        NSDictionary *dic=array[i];
        if ([dic[@"name"] isEqualToString:self.model.name]) {
            [array removeObjectAtIndex:i];
        }
    }
    [NSKeyedArchiver archiveRootObject:array toFile:entityArchive];
    NSMutableArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:entityArchive];
    NSLog(@"%@",array2);
    
    NSDictionary * d1 = @{
        @"name":self.model.name,
        @"time":[self getCurrentTimes],
    };
    [array insertObject:d1 atIndex:0];
    [NSKeyedArchiver archiveRootObject:array toFile:entityArchive];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"historyNotification" object:self userInfo:nil];
}
-(void)collectdata{
    //创建一个归档文件夹
    NSArray *library = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *strLib = [[library objectAtIndex:0] stringByAppendingPathComponent:@"archive"];
    BOOL directory = YES;
    if (![[NSFileManager defaultManager] fileExistsAtPath:strLib isDirectory:&directory])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:strLib withIntermediateDirectories:NO attributes:nil error:nil];
    }
    //归档
    NSString *entityArchive = [strLib stringByAppendingPathComponent:[NSString stringWithFormat:@"collectDataArchive%@",[Config getID]]];
//    [NSKeyedArchiver archiveRootObject:data toFile:entityArchive];
    //数据源从归档中读出
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:entityArchive];
    NSLog(@"%@",array);
    if(array.count==0){
        array=[NSMutableArray array];
    }
    if (self.model.isCollect==NO) {
        
        NSDictionary * d1 = @{
            @"name":self.model.name,
        };
        [array insertObject:d1 atIndex:0];
        [NSKeyedArchiver archiveRootObject:array toFile:entityArchive];
        NSMutableArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:entityArchive];
        NSLog(@"%@",array2);
    }else{
        for (int i=0; i<array.count; i++) {
            NSDictionary *dic=array[i];
            if ([dic[@"name"] isEqualToString:self.model.name]) {
                [array removeObjectAtIndex:i];
            }
        }
        [NSKeyedArchiver archiveRootObject:array toFile:entityArchive];
        NSMutableArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:entityArchive];
        NSLog(@"%@",array2);
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"foodCollcetNotification" object:self userInfo:nil];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.steps.count;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellIdentifier1 = @"CPFoodDetailsCell";//定义一个可重用标识
    PUFoodDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier1 forIndexPath:indexPath];
    CPStepModel *model = self.model.steps[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
